<template>
  <div class="article-list">
    <!-- 一个事件onload ,finished  ,v-model -->
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      success-text="刷新成功"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="加载失败"
      >
        <article-item
          :article="item"
          v-for="(item, index) in list"
          :key="index"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from "@/api/article";
import articleItem from "./article-item.vue";
export default {
  components: { articleItem },
  name: "ArticleList",

  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      error: false,
      isLoading: false,
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad(str) {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        let { data } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: this.timestamp,
          with_top: 0,
        });
        // console.log(1);
        // console.log(data);
        this.list.push(...data.data.results);
        this.loading = false;
        if (data.data.results.length < 10) {
          this.finished = true;
        } else {
          this.timestamp = data.data.pre_timestamp;
        }
      } catch (error) {
        console.log(error);
        this.$toast.fail("获取文章失败");
        if (str === "refresh") {
          this.list.unshift(...data.data.results);
        } else {
          this.list.push(...data.data.results);
        }
        this.loading = false;
        this.error = true;
      }
    },
    async onRefresh() {
      (this.finished = false), (this.timestamp = Date.now());
      try {
        await this.onLoad("refresh");
      } catch (error) {
        console.log(error);
      }
      this.isLoading = false;
    },
  },
};
</script>

<style scoped lang="less">
.article-list {
  // 百分比单位是相对于父元素的
  // height: 100%;

  // 视口（在移动端是布局视口）单位：vw 和 vh，不受父元素影响
  // 1vw = 视口宽度的百分之一
  // 1vh = 视口高度的百分之一
  height: 79vh;
  overflow-y: auto;
}
</style>